<template>
  <div class="zoomze-form">
    <form v-if="formData && formData.length > 0">
      <p class="progress">表单附件</p>
      <van-cell-group class="group-wrap">
        <!-- 附件 -->
        <div class="custom-cell less-padding" v-for="(formItem, formIndex) in formData" :key="formIndex">
          <div class="cell-title" :class="{'van-cell--required' : formItem.checked == '1'}">{{ formItem.form_name }}</div>
          <div class='preview-wrap'>
            <div class="preview-item-file" v-for="(file, fileIndex) in formItem.files">
              <span class="van-ellipsis">
                <img :src="$common.fileIcon(fileName(file.fileaddr, 'type'))">
                <span class="file-name" @click="previewFile(file)">{{ fileName(file.fileaddr, 'fullName') }}</span>
              </span>
              <van-icon class="close-button" name="clear" @click="deleteItem(formItem, file, fileIndex)"></van-icon>
            </div>
            <van-uploader multiple :before-read="beforeRead" :after-read="(file) => afterRead(file, 'file', formItem)" accept="*"/>
          </div>
        </div>
      </van-cell-group>
    </form>
  </div>
</template>

<script type="text/javascript">
  export default {
    props: {
      files: {
        type: Array,
        required: true
      }
    },
    data(){
      return {
        formData: [],
      }
    },
    watch: {
      'files': {
        handler(newV, oldV) {
          if (newV) {
            this.formData = this.$common.deepCopy(this.files)
          }
        }
      }
    },
    mounted() {
      this.formData = this.$common.deepCopy(this.files)
    },
    methods: {
      /**
       * 处理文件名称
       * @param  {String} url  文件地址(包含文件名, 文件类型)
       * @param  {String} type 截取类型 name 只需要名称 type 相只需要文件类型 fullName 返回完整文件名
       * @return {String}      截取后的名称
       */
      fileName(url, type) {
        let fullName   = !url.split('@daxsdfcsgr6time666@')[1] ? url : url.split('@daxsdfcsgr6time666@')[1]
        let pointCount = fullName.split('.').length
        let fileType   = fullName.split('.')[pointCount - 1]
        switch(type){
          case 'name':
            return fullName.split('.', pointCount - 1).join('.');
          case 'type':
            return fileType;
          case 'fullName':
          default:
            return fullName;
        }
      },
      beforeRead(file) {
        let flag = true
        if(file.type) { // 单个文件
          if(file.size > 20*1024*1024) {
            this.$dialog.alert(`{file.name} - 文件大于20MB`)
            flag = false
          }
        } else { // 多文件 多次调用
          file.forEach(fileItem => {
            if(fileItem.size > 20*1024*1024) {
              this.$dialog.alert({message: `${fileItem.name} - 文件大于20MB , 上传已终止!`})
              flag = false
            }
          })
        }
        return flag
      },
      /**
       * 成功读取文件后 进行上传
       * @param  {File}   file     文件
       * @param  {String} type     类型 (预留内容)
       * @param  {Object} formItem 表单formItem
       */
      afterRead(file, type, formItem) {
        let self = this
        self.$bridge.callHandler('navKeepView')
        let formData = new FormData()
        formData.append('file', file.file)
        formData.append('do', 'file')
        this.$toast({
          message: '上传中...',
          duration: 0,
          overlay: true,
          forbidClick: true,
          className: 'loading-toast',
          icon: require('../assets/loading.gif'),
        })
        let config = {
          headers: { //添加请求头
            'Content-Type': 'multipart/form-data'
          },
          url: `${this.$common.basePath}login.php`,
          data: formData,
          method: 'POST'
        }
        this.$axios(config).then(res => {
          self.$bridge.callHandler('cancelNavKeepView')
          formItem.files.push({fileaddr: res.data.url})
          this.$nextTick(_ => {
            this.$toast.clear()
          })
        }).catch(err => {
          self.$bridge.callHandler('cancelNavKeepView')
          console.log(err)
          this.$toast({
            icon: 'cross',
            message: err.msg ? err.msg : '上传失败!'
          })
        })
      },
      /**
       * 点击预览附件
       * @param  {[type]} item [description]
       * @return {[type]}      [description]
       */
      previewFile(item) {
        // console.log(item)
        this.$bridge.callHandler('showPreview', {
          url: `${this.$common.filePath}${item}`,
          fileName:  this.fileName(item, 'fullName') || item
        })
        window.open(`${this.$common.filePath}${item}?filename=${this.fileName(item, 'fullName')}`)
      },
      /**
       * 删除附件
       * @param  {Object} formItem 当前formItem
       * @param  {Number} imgIndex 对应图片序列
       */
      deleteItem(formItem, file, imgIndex) {
        // console.log(file)
        this.$bridge.callHandler('navKeepView')
        if (file.id) {
          this.$dialog.confirm({
            title: '提示',
            message: '是否确认删除该文件？删除后不可恢复'
          }).then(() => {
            // on confirm
            let config = {
              method: 'post',
              url: `${this.$common.basePath}aatp5/public/index.php/formfile/form_file/file_del`,
              data: {
                user_id: this.$store.state.userId,
                id: file.id
              }
            }
            this.$axios(config).then(res => {
              // console.log(res.msg)
              this.$bridge.callHandler('cancelNavKeepView')
              formItem.files.splice(imgIndex, 1)
            }).catch(err => {
              console.log(err)
              this.$bridge.callHandler('cancelNavKeepView')
            })
          }).catch((err) => {
            // on cancel
            console.log(err)
          });
        } else {
          this.$dialog.confirm({
            title: '提示',
            message: '是否确认删除该文件？删除后不可恢复'
          }).then(() => {
            // on confirm
            this.$bridge.callHandler('cancelNavKeepView')
            formItem.files.splice(imgIndex, 1)
          }).catch((err) => {
            // on cancel
            this.$bridge.callHandler('cancelNavKeepView')
            console.log(err)
          });
        }
        
      },
      /**
       * 验证表单内容 获取当前表单的最终编辑结果 （外部父组件调用）验证失败 返回false
       * @return {Object} 格式化的最终表单数据 用于保存
       */
      getFormData() {
        let result = []
        let flag = true
        let validateData = this.$common.deepCopy(this.formData).reverse()
        validateData.forEach((item, index) => {
          // console.log(item)
          if(item.checked == '1' && (item.files == [] || item.files == '')) {
            flag = false
            this.$toast({
              message: `${item.form_name} 为空!`,
              icon: 'cross'
            })
          } else { // 数据不为空 ,输出数据
            result.push({id: item.formid, files:item.files})
          }

        })
        // console.log(result)
        // console.log(flag ? result : flag)
        return flag ? result : flag
      }
    }
  }
</script>

<style  type="text/css" lang="less">
  .zoomze-form {
    .group-wrap {
      margin: 12px 0;
    }
    .less-padding {
      padding: 10px 16px 4px 16px;
    }
    .progress {
      margin-top: 20px;
      margin-left: 15px;
      margin-bottom: 10px;
      font-size: 15px;
      color: #999999;
    }

    .custom-cell {
      width: calc( 100% - 32px );
      padding: 6.5px 16px;
      word-wrap: nowrap;
      overflow: hidden;
      &.less-padding {
        padding: 10px 16px 4px 16px;
      }
      .cell-title {
        margin-bottom: 12px;
      }
      &.cell-added {
        display: flex;
        justify-content: space-between;
        .cell-title {
          margin-bottom: 0;
          width: 70px;
        }
        .van-ellipsis {
        }
      }
    }
  }
  
</style>